﻿using Treca.Base_SysManage.Entity;
using Treca.Business.Base_SysManage;
using Treca.Message.Business;
using Treca.Message.Entity;
using Treca.Util;
using Treca.Util.PublishSubscribe;
using EFCore.Sharding;
using LinqKit;
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace Treca.Message
{
    public class SignalRLoginEvent : IEventHandler<string>
    {

        public AjaxResult Run(string Command, string T)
        {
            RunMessage(Command, T);
            return AjaxHelper.Success();
        }
        public AjaxResult RunMessage(string Command, string values)
        {
            if (Command == "SignalRLogin")
            {
                var s = MessageHub.OnlineUser;
                var userProcess = values;
                SdkPubSubCenter.PublishCustom("FlashMessage", userProcess);
                //hub.Clients.All.SendAsync("MessageInfo_" + userProcess, new {  Header="你有"+ userMessages.Count+ "条信息",Data = userMessages });
            }
            if (Command == "FlashMessage")
            {
                var s = MessageHub.OnlineUser;
                var userProcess = values;
                IRepository service = AutofacHelper.GetScopeService<IRepository>();
                IHubContext<MessageHub> hub = AutofacHelper.GetService<IHubContext<MessageHub>>();
                var user_message = from usermsg in service.GetIQueryable<base_user_message>().AsExpandable()
                                   join msg in service.GetIQueryable<base_message>() on usermsg.MessageId equals msg.Id
                                   where usermsg.IsRead == "0" && usermsg.UserId == userProcess
                                   orderby usermsg.CreateDate descending
                                   select msg;
                var clientsId = s.Where(t => t.UserID == userProcess).Select(t => t.ConnectionId).ToList();
                var Count = user_message.Count();
                var userMessages = user_message.Take(4).ToList();
                if (clientsId.Count > 0)
                {
                    hub.Clients.Clients(clientsId).SendAsync("MessageInfo_" + userProcess, new { Header = "你有" + Count + "条信息未读", Count = Count, Data = userMessages });
                }
                //hub.Clients.All.SendAsync("MessageInfo_" + userProcess, new {  Header="你有"+ userMessages.Count+ "条信息",Data = userMessages });
            }
            return AjaxHelper.Success();
        }
        public Task<AjaxResult> RunAsync(string Command, string T)
        {
            JobHelper.SetIntervalJob(() =>
            {
                RunMessage(Command, T);
            }, TimeSpan.Zero, TimeSpan.Zero);
            return null;
        }
    }
}
